package com.leyou.task;

import com.leyou.lock.RedisLock;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class HelloJob {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Scheduled(cron = "0/10 * * * * ?")
    public void HelloJob(){
        RedisLock lock = new RedisLock(redisTemplate, "lock");
        Boolean islock = lock.tryLock(10, TimeUnit.MINUTES);

        if (!islock){
            log.info("获取锁失败，停止定时任务");
            return;
        }
        try {
            log.info("获取锁成功,执行定时任务");
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            log.error("执行任务异常"+e);
            e.printStackTrace();
        }finally {
            lock.unLock();
        }
    }
}
